package com.zjitc.web.controller;

import com.zjitc.pojo.Cart;
import com.zjitc.pojo.User;
import com.zjitc.service.CartService;
import com.zjitc.service.ShopService;
import com.zjitc.service.UserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private UserSerivce userSerivce;

    @RequestMapping("insert")
    @ResponseBody
    public void insert(Cart cart, HttpSession session){
        User user = (User)session.getAttribute("user");
        if (user.getU_id()==0){
            user=userSerivce.queryUserByUsername(user.getUsername());
            session.setAttribute("user",user);
        }
        cart.setU_id(user.getU_id());
        cart.setProduct(shopService.queryProductById(cart.getP_id()));
        cartService.insertCart(cart);
        List<Cart> carts = getCarts(cart.getU_id());
        session.setAttribute("carts",carts);
    }

    @RequestMapping("delete")
    @ResponseBody
    public void delete(int id,HttpSession session){
        cartService.deleteCartById(id);
        User user = (User)session.getAttribute("user");
        List<Cart> carts = getCarts(user.getU_id());
        session.setAttribute("carts",carts);
    }

    public List<Cart> getCarts(int u_id){
        List<Cart> carts = cartService.queryCartByUserAll(u_id);
        for (Cart c : carts) {
            c.setProduct(shopService.queryProductById(c.getP_id()));
        }
        return carts;
    }

//    @RequestMapping("show")
//    public String show(HttpSession session){
//        List<Cart> carts = cartService.queryCartByUserAll();
//        session.setAttribute("carts",carts);
//        return "redirect:/shop/home.do";
//    }

}
